package com.beetle123.utils;

import javafx.application.Platform;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;

import java.io.*;

/**
 * @author yuanlong.chen
 * @date 2020/10/31
 */
public class MyUtils {
    private final static String DOT_JAR = ".jar";
    private final static String DOT_EXE = ".exe";

    public static String readFile(String fileName) {
        File file = new File(fileName);
        if (!file.exists()) {
            throw new RuntimeException("文件" + fileName + "不存在");
        }
        BufferedReader reader = null;
        StringBuilder sb = new StringBuilder();
        try {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            reader.close();
        } catch (IOException e) {
            LogUtils.println(getStackTrace(e));
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
        return sb.toString();
    }

    public static String getBasePath() {
        try {
            String path = MyUtils.class.getProtectionDomain().getCodeSource().getLocation().getPath();
            System.out.println(path);
            if (path.endsWith(DOT_JAR) || path.endsWith(DOT_EXE)) {
                path = path.substring(0, path.lastIndexOf("/") + 1);
            }
            return path;
        } catch (Exception e) {
            System.err.println(getStackTrace(e));
        }
        return "";
    }

    public static String getStackTrace(Throwable aThrowable) {
        final Writer result = new StringWriter();
        final PrintWriter printWriter = new PrintWriter(result);
        aThrowable.printStackTrace(printWriter);
        return result.toString();
    }


    public static String getConfig() {
        String path = getBasePath() + "/config.json";
        return readFile(path);
    }

    public static void alert(String msg) {
        new Alert(Alert.AlertType.NONE, msg, new ButtonType[]{ButtonType.CLOSE}).show();
    }

    public static void alert(String msg, int timeoutSecond) {
        Alert alert = new Alert(Alert.AlertType.NONE, msg, new ButtonType[]{ButtonType.CLOSE});
        new Thread(() -> {
            try {
                Thread.sleep(timeoutSecond * 1000);
                Platform.runLater(() -> {
                    alert.close();
                });
            } catch (Exception e) {
            }
        }).start();
        alert.show();
    }


}
